import { Button, Table } from "antd";
import axios from "axios"
import usePublishInfo from "../../unti/usePublishInfo";
export default function PublishList({publishState}) {
    const {dataSource,setDataSource}=usePublishInfo(publishState);
    // 因为dataSource本身是一个对象 所以tableDate是一个双重对象

    const columns = [
    {
      title: "新闻标题",
      dataIndex: "title",
      render:(title,item)=>{
        return <a href={`#/news-manage/preview/${item.id}`}>{title}</a>
      }
    },
    {
      title: "作者",
      dataIndex: "author",
    },
    { 
      title: "新闻分类",
      dataIndex: "category",
      key: "category",
      render: (category) => {
        return <div>{category.title}</div>;
      },
    },
    {
      title: "操作",
      render: (item) => {
        // item就是当前行
        return (
          <>
            {publishState==1?
            <Button
              color="blue"
              onClick={()=>uploadNews(item)}
            >
              发布
            </Button>:publishState==2?
            <Button
              color="blue"
              onClick={()=>BreakdownNews(item)}
            >
              下线
            </Button>:
            <Button
              color="red"
              onClick={()=>deleteNews(item)}
              danger
            >
              删除
            </Button>
            }
          </>
        );
      },
    },
  ];

  const uploadNews = async (item) => {
      await axios.patch(`http://localhost:3000/news/${item.id}`, {
        publishState: 2,
        publishTime: Date.now()
      });
      // 更新本地状态
      setDataSource(dataSource.filter((data) => data.id !== item.id));
  };
  const BreakdownNews = async (item) => {
    await axios.patch(`http://localhost:3000/news/${item.id}`, {
        publishState: 3,
    });
      // 更新本地状态
    setDataSource(dataSource.filter((data) => data.id !== item.id));
  }
  const deleteNews=async(item)=>{
    await axios.delete(`http://localhost:3000/news/${item.id}`);
    // 更新本地状态
    setDataSource(dataSource.filter((data) => data.id !== item.id));
  }
  return (
    <div>
      <Table
        dataSource={dataSource}
        columns={columns}
        pagination={{
          pageSize: 5,
        }}
        rowKey={(item) => item.id}
      />
    </div>
  );
}